package com.cgbl.cg.view

import android.annotation.TargetApi
import android.app.Dialog
import android.content.Context
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.FrameLayout
import androidx.core.content.res.ResourcesCompat
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient

import com.robot.base.view.webview.WebLayout


import android.widget.LinearLayout
import com.blankj.utilcode.util.ActivityUtils
import com.cgbl.cg.R
import android.webkit.WebResourceRequest
import com.just.agentweb.WebViewClient


class WebViewDialog(context: Context) : Dialog(context, R.style.common_dialog),
    CustomWebClient.WebClientCallback {
    private var mWebView // 显示网页
            : WebView? = null

    private var countDownTimer: CountDownTimer? = null

    init {
        initWindows()
        setContentView(R.layout.sco_activity_web_view)
        initView()

        setCancelable(false)
        setCanceledOnTouchOutside(false)
    }


    private fun initView() {
        initWebView()

//        ivClose.setOnClickListener {
//            dismiss()
//        }
//        ivBack.setOnClickListener {
//            goBack()
//        }
//
//        llEscape.setOnClickListener {
//            dismiss()
//        }
//        ivInnerClose.setOnClickListener {
//            dismiss()
//        }


        //弹窗模式下，webview背景变成透明
//        flWebViewContainer.setBackgroundColor(
//            ResourcesCompat.getColor(
//                context.resources,
//                android.R.color.transparent,
//                null
//            )
//        )
    }

    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            //do you  work
//            Log.i("Info", "BaseWebActivity onPageStarted")
        }
    }
    private val mWebChromeClient: com.just.agentweb.WebChromeClient =
        object : com.just.agentweb.WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
//            if (mTitleTextView != null) {
//                mTitleTextView.setText(title)
//            }
            }
        }

    /**
     * 初始化webView
     */
    private fun initWebView() {
//        val agentWeb = AgentWeb.with(ActivityUtils.getTopActivity())
//            .setAgentWebParent(flWebViewContainer, FrameLayout.LayoutParams(-1, -1))
//            .useDefaultIndicator()
//            .setWebChromeClient(mWebChromeClient)
//            .setWebViewClient(mWebViewClient)
//            .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
//            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
//            .setWebLayout(WebLayout(ActivityUtils.getTopActivity()))
//            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
//            .interceptUnkownUrl() //拦截找不到相关页面的Scheme
//            .createAgentWeb()
//            .ready()
//            .go("https://www.baidu.com")
//        agentWeb.agentWebSettings.webSettings.useWideView/Port = false
//        agentWeb.agentWebSettings.webSettings.loadWithOverviewMode = false

//        mWebView = WebView(context)
//        mWebView?.isHorizontalScrollBarEnabled = false //水平不显示
//        mWebView?.isVerticalScrollBarEnabled = false //垂直不显
//        mWebView?.setBackgroundColor(0)//webview背景全透明
//        mWebView?.background?.mutate()?.alpha = 0
//        flWebViewContainer.addView(mWebView)
//
//        val webSettings = mWebView!!.settings
//        val sb = StringBuilder()
//        sb.append(webSettings.userAgentString)
//            .append("|")
//            .append("Android-WebView")
//            .append("|")
//            .append(AppUtils.getAppPackageName())
//            .append("|")
//            .append("1.1") //app版本号
//        webSettings.userAgentString = sb.toString()
//        mWebView!!.webViewClient = CustomWebClient(this)
//        mWebView!!.webChromeClient = SimpleWebChromeClient()
//        webSettings.javaScriptEnabled = true
//        webSettings.useWideViewPort = true
//        webSettings.domStorageEnabled = true
//        webSettings.loadWithOverviewMode = true
//        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//            setMined(webSettings)
//        }
//        mWebView!!.overScrollMode = View.OVER_SCROLL_NEVER
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun setMined(webSettings: WebSettings) {
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
    }


    internal inner class SimpleWebChromeClient : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (newProgress >= 90) { //加载进度大于等于90时，隐藏进度条

            }
        }
    }

    private fun initWindows() {
        val win = this.window
        win?.requestFeature(Window.FEATURE_NO_TITLE)
        win?.decorView?.setPadding(0, 0, 0, 0)
        val lp = win?.attributes
        lp?.width = WindowManager.LayoutParams.WRAP_CONTENT
        lp?.height = WindowManager.LayoutParams.WRAP_CONTENT
//        lp?.windowAnimations = R.style.LightInAndOutStyle
        lp?.gravity = Gravity.CENTER
        win?.attributes = lp
        win?.setBackgroundDrawableResource(android.R.color.transparent)
    }

    fun setSizes(width: Int, height: Int) {
        val win = this.window
        val lp = win?.attributes
        lp?.width = SizeUtils.dp2px(width.toFloat())
        lp?.height = SizeUtils.dp2px(height.toFloat())
        win?.attributes = lp
    }

    fun load(
        webUrl: String?,
        title: String,
        closeTime: Int,
        haveFrame: Boolean
    ) {
//        if (mWebView != null && !TextUtils.isEmpty(webUrl)) {
//            mWebView!!.loadUrl(webUrl)
//        }
//        tvTitle.text = title
//        if (haveFrame) {
//            clWebTitle.visibility = View.VISIBLE
//            llEscape.visibility = View.GONE
//            ivInnerClose.visibility = View.GONE
//        } else {
//            clWebTitle.visibility = View.GONE
//        }
//        if (closeTime > 0) {
//            tvBack.visibility = View.VISIBLE
//            if (!haveFrame) {
//                llEscape.visibility = View.VISIBLE
//                ivInnerClose.visibility = View.GONE
//            }
//            if (countDownTimer == null) {
//                countDownTimer = object : CountDownTimer(closeTime * 1000L, 1000) {
//                    override fun onFinish() {
//                        dismiss()
//                    }
//
//                    override fun onTick(millisUntilFinished: Long) {
//                        val seconds = (millisUntilFinished / 1000).toString()
//                        tvBack.text = seconds
//                        tvEscape.text = "跳过 $seconds"
//                    }
//
//                }.start()
//            } else {
//                countDownTimer!!.cancel()
//                countDownTimer!!.start()
//            }
//        } else {
//            if (!haveFrame) {
//                llEscape.visibility = View.GONE
//                ivInnerClose.visibility = View.VISIBLE
//            }
//            countDownTimer?.cancel()
//            countDownTimer = null
//        }
    }

    override fun show() {
        if (!isShowing) {
//            if (flWebViewContainer.childCount == 0) {
//                initWebView()
//            }
        }
        super.show()
    }

    override fun dismiss() {
        if (isShowing) {
            countDownTimer?.cancel()
            window?.let { KeyboardUtils.hideSoftInput(it) }
//            tvBack.visibility = View.GONE
            mWebView?.run {
                clearHistory()
            }
        }
        super.dismiss()
    }

    override fun onPageFinished(view: WebView?, url: String?) {
    }

    override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
    }

    override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
    }

    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        return false
    }

    override fun onLoadResource(view: WebView?, url: String?) {
    }

    /**
     * h5界面可返回上一个界面时，按下后退键返回上一个界面的处理
     */
    private fun goBack(): Boolean {
        if (mWebView != null && mWebView!!.canGoBack()) {
            mWebView!!.goBack()
            return false
        } else {
            dismiss()
        }
        return true
    }

    fun onDestroy() {
        if (mWebView != null) {//防止内存泄露
            mWebView!!.loadUrl("about:blank")
//            flWebViewContainer.removeAllViews()
            mWebView!!.visibility = View.GONE
            mWebView!!.run {
                stopLoading()
                settings.javaScriptEnabled = false
                clearHistory()
                clearView()
                removeAllViews()
                destroy()
            }
            mWebView = null
        }

        System.gc()
    }
}